/**
 * 将一个对象的属性值深拷贝到另一个对象具有相同属性的属性中去
 * @param flatten 源对象
 * @param target 目标对象
 */
function deepCopyProperties(flatten: Record<string, any>, target: Record<string, any>) {
  for (const key in flatten) {
    if (Object.prototype.hasOwnProperty.call(flatten, key) && Object.prototype.hasOwnProperty.call(target, key)) {
      if (typeof flatten[key] === 'object' && flatten[key] !== null && typeof target[key] === 'object' && target[key] !== null) {
        // 递归拷贝对象属性值
        deepCopyProperties(flatten[key], target[key])
      } else {
        // 深拷贝基本类型属性值
        target[key] = flatten[key]
      }
    }
  }
}

/**
 * 将一个嵌套对象展平为扁平化对象
 * @param obj 待展平的对象
 * @returns 扁平化后的对象
 */
function flattenObject(obj: Record<string, any>): Record<string, any> {
  let flattened: Record<string, any> = {}
  for (const key in obj) {
    if (Array.isArray(obj[key])) {
      flattened[key] = obj[key]
    } else if (Object.prototype.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === 'object' && obj[key] !== null) {
        const nested = flattenObject(obj[key])
        flattened = { ...flattened, ...nested }
      } else {
        flattened[key] = obj[key]
      }
    }
  }

  return flattened
}
/**
 * 将一个对象的属性值深拷贝到另一个对象具有相同属性的属性中去
 * @param source 源对象
 * @param target 目标对象
 */
export default function deepCopy(source: Record<string, any>, target: Record<string, any>) {
  const flatten = flattenObject(source)
  deepCopyProperties(flatten, target)
}
